﻿// <copyright file="AnalyticsCategoryLayout.xaml.cs" company="Microsoft Corporation">
// Copyright (c) 2009 Microsoft Corporation All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2009-06-05</date>
// <summary>The AnalyticsCategoryLayout class definition</summary>

namespace Microsoft.WebAnalytics.Design.Editors
{
    using System;
    using System.Diagnostics;
    using System.Globalization;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Windows;
    using System.Windows.Controls;

    /// <summary>
    /// Interaction logic for AnalyticsCategoryLayout.XAML
    /// </summary>
    public partial class AnalyticsCategoryLayout : UserControl
    {
        #region Fields
        /// <summary>
        /// the Registry key
        /// </summary>
        private const string KeyName = @"Software\Microsoft\Silverlight Analytics Framework.4";

        /// <summary>
        /// The type being inspected
        /// </summary>
        private Type objectType;
        #endregion

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the AnalyticsCategoryLayout class.
        /// </summary>
        public AnalyticsCategoryLayout()
        {
            this.InitializeComponent();

            this.Loaded += new RoutedEventHandler(this.AnalyticsCategoryLayout_Loaded);
        }
        #endregion

        #region Implementation

        /// <summary>
        /// Create a Hashed member name
        /// </summary>
        /// <param name="memberName">the name of the class member</param>
        /// <returns>the Hashed filename</returns>
        private static string CreateHashedMemberName(string memberName)
        {
            // Assume memberName contains the member name of the
            // topic to show.
            var pageName = string.Format(
                CultureInfo.InvariantCulture,
                "{0:X}",
                memberName.GetHashCode());

            // Show the topic in the help file.  Remember to add
            // the "html\" folder name and the ".htm" extension.
            return string.Format(CultureInfo.InvariantCulture, @"html\{0}.htm", pageName);
        }

        /// <summary>
        /// Create a member name using the help filename format
        /// </summary>
        /// <param name="memberName">the name of the type and member</param>
        /// <returns>the relative URL for the help file</returns>
        private static string CreateMemberName(string memberName)
        {
            Regex invalidCharacters = new Regex("[ :.`#<>*?]");

            // Assume memberName contains the member name of the
            // topic to show.
            string pageName = invalidCharacters.Replace(
                memberName, "_");

            // Show the topic in the help file.  Remember to add
            // the "html\" folder name and the ".htm" extension.
            return string.Format(CultureInfo.InvariantCulture, @"html\{0}.htm", pageName);
        }

        /// <summary>
        /// Set the hyperlinks when the layout loads 
        /// </summary>
        /// <param name="sender">the AnalyticsCategoryLayout object</param>
        /// <param name="e">the routed event arguments</param>
        private void AnalyticsCategoryLayout_Loaded(object sender, RoutedEventArgs e)
        {
            this.SetHyperlinks();
        }

        /// <summary>
        /// Set the hyperlinks for the help/search
        /// </summary>
        private void SetHyperlinks()
        {
            var entry = this.DataContext as Microsoft.Windows.Design.PropertyEditing.CategoryEntry;

            if (entry == null)
            {
                return;
            }

            var first = entry.Properties.FirstOrDefault();

            if (first == null)
            {
                return;
            }

            this.objectType = first.Identifier.DeclaringType;

            this.SearchOnlineLink.NavigateUri = new Uri(string.Format(CultureInfo.InvariantCulture, Properties.Resources.BingUrlFormat, this.objectType.Name), UriKind.Absolute);

            this.SearchIssues.NavigateUri = new Uri(string.Format(CultureInfo.InvariantCulture, Properties.Resources.IssueUrlFormat, this.objectType.Name));

            this.SearchDiscussions.NavigateUri = new Uri(string.Format(CultureInfo.InvariantCulture, Properties.Resources.DiscussionUrlFormat, this.objectType.Name));
        }

        /// <summary>
        /// Opens the Silverlight Analytics Framework.chm help file with the 
        /// topic being the class of the selected object.
        /// </summary>
        /// <param name="sender">the button</param>
        /// <param name="e">the routed event arguments</param>
        private void OpenHelp(object sender, RoutedEventArgs e)
        {
            var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(KeyName, false);

            if (key == null)
            {
                System.Windows.MessageBox.Show(
                    Properties.Resources.InstallationError, 
                    Properties.Resources.SilverlightAnalyticsFramework, 
                    MessageBoxButton.OK, 
                    MessageBoxImage.Error);

                return;
            }
            
            var installDir = key.GetValue("InstallDir") as string;

            key.Close();

            var helpPath = installDir + @"Help\Microsoft Silverlight Analytics Framework.chm";

            if (!System.IO.File.Exists(helpPath))
            {
                var message = string.Format(CultureInfo.CurrentCulture, Properties.Resources.HelpFileDoesNotExist, helpPath);

                System.Windows.MessageBox.Show(message, Properties.Resources.SilverlightAnalyticsFramework, MessageBoxButton.OK, MessageBoxImage.Error);

                return;
            }

            var arguments = string.Format(
                CultureInfo.InvariantCulture,
                "mk:@MSITStore:{0}::{1}",
                helpPath,
                CreateMemberName("T:" + this.objectType.FullName));

            System.Diagnostics.Debug.WriteLine(arguments);

            System.Diagnostics.Process.Start("HH.exe", arguments);
        }

        /// <summary>
        /// Request that the navigation use the default browser
        /// </summary>
        /// <param name="sender">the Hyperlink</param>
        /// <param name="e">the request navigate event arguments</param>
        private void OnRequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
        {
            Process.Start(e.Uri.ToString());
        }
        #endregion
    }
}
